import cluster from "node:cluster";
import { createServer } from "node:http";
import { pid } from "node:process";

const numCPUs = require("node:os").availableParallelism();

if (cluster.isPrimary) {
  console.log(`Primary ${pid} is running`);

  // Fork workers.
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on("exit", (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });
} else {
  // Workers can share any TCP connection
  // In this case it is an HTTP server
  createServer((req, res) => {
    res.writeHead(200);
    res.end("hello world\n");
  }).listen(8000);

  console.log(`Worker ${pid} started`);
}
